﻿
using Core.FrameWork.Commons.Hepler.Validate;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Core.FrameWork.Commons.Extensions
{
    /// <summary>
    /// ReqAttributeExtend
    /// </summary>
    public static class AttributeExtend
    {
        /// <summary>
        /// 验证
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static ValidateResult Validate<T>(this T t)
            where T : ReqBaseModel, new()
        {
            Type type = t.GetType();
            List<string> listError = new List<string>();
            foreach (var prop in type.GetProperties())
            {
                if (prop.IsDefined(typeof(AbstractValidateAttribute), true))
                {
                    object oValue = prop.GetValue(t);
                    foreach (AbstractValidateAttribute attribute in prop.GetCustomAttributes(typeof(AbstractValidateAttribute), true))
                    {
                        var result = attribute.Validate(oValue);
                        if (!result.Status)
                        {
                            string displayName = GetDisplayName(prop);
                            listError.Add($"字段{{{displayName}}}{result.Message}");
                            break;
                        }
                    }
                }
            }
            return new ValidateResult() { ListErrorMessage = listError };
        }

        /// <summary>
        /// 获得DisplayName
        /// </summary>
        /// <param name="prop"></param>
        /// <returns></returns>
        private static string GetDisplayName(PropertyInfo prop)
        {
            if (prop.IsDefined(typeof(DisplayAttribute), true))
            {
                DisplayAttribute display = prop.GetCustomAttribute(typeof(DisplayAttribute)) as DisplayAttribute;
                return display.Description;
            }
            return prop.Name;
        }
    }
}
